package io.gitee.kotle.demo.mvvm_demo.pic

import android.os.Bundle
import android.os.Environment
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import io.gitee.kotle.android.utils.*
import io.gitee.kotle.base.library.BaseBindingFragment
import io.gitee.kotle.demo.R
import io.gitee.kotle.demo.databinding.FragmentFileDownloadBinding
import java.io.File


class FileDownloadFragment : BaseBindingFragment<FragmentFileDownloadBinding>() {


    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
//        downloadPicDemo()
        appCompatActivity.setResult(778899)
        mBinding.cancel.onClick {
            startFragment<FileDownloadFragment> {
                activityForResult.launch(it) {
                    println()
                }
            }
        }
    }

    val activityForResult = activityForResult()


    private fun downloadPicDemo() {
        val oldFile =
            File(appCompatActivity.getExternalFilesDir(Environment.DIRECTORY_DCIM)!!.absolutePath + "/test.apk")
        if (oldFile.exists()) {
            oldFile.delete()
//            requireActivity().openFileByOtherApp(oldFile)
//            return
        }
        mBinding.progressBar.progress = 0f
        val job = lifecycleScope.launchWhenCreated {
            val file = OkHttpCertUtil.createCertOkHttpBuilder().build().downloadFile(
                "https://lf9-apk.ugapk.cn/package/apk/aweme/1015_180601/aweme_juyouliang_douyin_and15_v1015_180601_caf3_1637674311.apk?v=1637674322",
                appCompatActivity.getExternalFilesDir(Environment.DIRECTORY_DCIM)!!.absolutePath,
                "test.apk",
            ) { downloadLen, totalLen, progress ->
                mBinding.progressBar.post {
                    mBinding.progressBar.progress = progress / 100f
                    mBinding.progressBar.progressText = "${progress.keepTwoPoint()}"
                }
            }
            requireActivity().openFileByOtherApp(file)
        }

        mBinding.cancel.onClick {
            job.cancel()
        }
    }
}